package net.caixiaomi.info.ui.dialog;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import net.caixiaomi.info.R;
import net.caixiaomi.info.base.BaseDialogFragment;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.util.EventWhat;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Method;
import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;
import icepick.State;

/**
 * 倍数选择
 */

public class TrebleDialogFragment extends BaseDialogFragment implements TextWatcher {

    @BindView(R.id.num)
    EditText mNum;
    @BindView(R.id.treble)
    LinearLayout mTreble;
    @BindView(R.id.contentPanel)
    LinearLayout mNumKey;
    @State
    int mTrebleNum;

    private boolean mInit = true;

    @OnClick(R.id.btn_hide)
    void toHide() {
        dismiss();
    }

    @OnClick(R.id.btn_delete)
    void toDelete() {
        try {
            String text = mNum.getText().toString();
            String substring = text.substring(0, text.length() - 1);
            mNum.setText(substring);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.btn_done)
    void toDone() {
        try {
            String text = mNum.getText().toString();
            if (TextUtils.isEmpty(text)) {
                text = "1";
            }
            if (new BigDecimal(text).compareTo(new BigDecimal("0")) != 1) {
                text = "1";
            }
            EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_TREBLE, text));
            dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTrebleNum = getArguments().getInt("treble", 5);


    }

    @Override
    protected int layoutRes() {
        return R.layout.dialog_treble;
    }


    @Override
    protected void onViewCreated(@NonNull View view) {
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
        wlp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wlp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        wlp.gravity = Gravity.BOTTOM;
        window.setAttributes(wlp);
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        window.setBackgroundDrawable(new ColorDrawable(0xff000000));
        getDialog().getWindow().setLayout(dm.widthPixels, getDialog().getWindow().getAttributes().height);

        mNum.addTextChangedListener(this);
        mNum.setText(String.valueOf(mTrebleNum));
        disableShowSoftInput();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        int[] trebleArray = getResources().getIntArray(R.array.C_TREBLE);
        LinearLayout.LayoutParams VerticalLine = new LinearLayout.LayoutParams((int) getResources().getDimension(R.dimen.divider), ViewGroup.LayoutParams.MATCH_PARENT);
        LinearLayout.LayoutParams HorlLine = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.divider));

        StringBuilder stringBuilder = new StringBuilder();
        for (int index = 0; index < trebleArray.length; index++) {
            stringBuilder.setLength(0);
            stringBuilder.append(trebleArray[index]).append(getString(R.string.C_TREBLE_CHAT));
            TextView textView = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.view_textview, null);
            textView.setPadding(0, (int) getResources().getDimension(R.dimen.padding_12), 0, (int) getResources().getDimension(R.dimen.padding_12));
            textView.setText(stringBuilder);
            textView.setId(trebleArray[index]);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mInit) {
                        mInit = false;
                        mNum.setText(String.valueOf(v.getId()));
                    } else {
                        String num = mNum.getText().toString();
                        mNum.setText(String.valueOf(v.getId()));
                    }
                    AppHelper.sendStatistics("bsxuanzezc", new String[]{getString(R.string.C_TREBLE)}, new String[]{mNum.getText().toString().trim()});
                }
            });
            mTreble.addView(textView, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));

            if (index < trebleArray.length - 1) {
                TextView line = new TextView(getActivity());
                line.setBackgroundResource(R.color.divider);
                mTreble.addView(line, VerticalLine);
            }
        }
        for (int row = 0; row < 4; row++) {
            LinearLayout container = new LinearLayout(getActivity());
            for (int col = 1; col <= 3; col++) {
                int value = 3 * row + col;
                TextView textView = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.view_textview, null);
                textView.setPadding(0, (int) getResources().getDimension(R.dimen.padding_12), 0, (int) getResources().getDimension(R.dimen.padding_12));
                textView.setText(String.valueOf(value));
                if (value == 10) {
                    textView.setText("0");
                } else if (value > 10) {
                    textView.setText("");
                }
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView view = (TextView) v;
                        if (mInit) {
                            mInit = false;
                            mNum.setText(view.getText().toString());
                        } else {
                            String num = mNum.getText().toString();
                            mNum.setText(num + view.getText().toString());
                        }
                        AppHelper.sendStatistics("bsxuanzezc", new String[]{getString(R.string.C_TREBLE)}, new String[]{mNum.getText().toString().trim()});
                    }
                });
                container.addView(textView, new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
                if (col < 3) {
                    TextView line = new TextView(getActivity());
                    line.setBackgroundResource(R.color.divider);
                    container.addView(line, VerticalLine);
                }
            }
            mNumKey.addView(container, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

            if (row < 3) {
                TextView line = new TextView(getActivity());
                line.setBackgroundResource(R.color.divider);
                mNumKey.addView(line, HorlLine);
            }

        }

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (!TextUtils.isEmpty(s.toString())) {
            mNum.setSelection(mNum.getText().toString().length());
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    /**
     * 禁止Edittext弹出软件盘，光标依然正常显示。
     */
    public void disableShowSoftInput() {
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            mNum.setInputType(InputType.TYPE_NULL);
        } else {
            Class<EditText> cls = EditText.class;
            Method method;
            try {
                method = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                method.setAccessible(true);
                method.invoke(mNum, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
